package com.leviassaf.al_app_one;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;

public class MainActivity extends FragmentActivity {

	private static final int SPLASH = 0;
	private static final int SELECTION = 1;
	private static final int SETTINGS = 2;
	private static final int FRAGMENT_COUNT = SETTINGS + 1;

	private MenuItem menuItemSettings;
	private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
	private boolean booIsResumed = false;

	private UiLifecycleHelper uiLifecycleHelper;
	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			// TODO Auto-generated method stub
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//print Key-Hash to LogCat
		//getAppKeyHash();
		
		
		uiLifecycleHelper = new UiLifecycleHelper(this, statusCallback);
		uiLifecycleHelper.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragments[SPLASH] = (SplashFragment) fragmentManager.findFragmentById(R.id.splashFragment);
		fragments[SELECTION] = (SelectionFragment) fragmentManager.findFragmentById(R.id.selectionFragment);
		fragments[SETTINGS] = fragmentManager.findFragmentById(R.id.userSettingsFragment);
		
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
		for (int i = 0; i < fragments.length; i++){
			fragmentTransaction.hide(fragments[i]);
		}
		fragmentTransaction.commit();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		uiLifecycleHelper.onResume();
		booIsResumed = true;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		uiLifecycleHelper.onPause();
		booIsResumed = false;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		uiLifecycleHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		uiLifecycleHelper.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		uiLifecycleHelper.onSaveInstanceState(outState);
	}

	@Override
	protected void onResumeFragments() {
		// TODO Auto-generated method stub
		super.onResumeFragments();
		Session session = Session.getActiveSession();
		if (session != null && session.isOpened()){
			showFragment(SELECTION, false);
		}
		else{
			showFragment(SPLASH, false);
		}
	}

	private void onSessionStateChange(Session session, SessionState sessionState, Exception exception){
		if (booIsResumed){
			FragmentManager fragmentManager = getSupportFragmentManager();
			int intBackStackSize = fragmentManager.getBackStackEntryCount();
			for (int i = 0; i < intBackStackSize; i++){
				fragmentManager.popBackStack();
			}
			if (sessionState.isOpened()){
				showFragment(SELECTION, false);
			}
			else{
				showFragment(SPLASH, false);
			}
		}
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}
//
	public void showFragment(int fragmentIndex, boolean addToBackStack){
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
		for (int i = 0; i < fragments.length; i++){
			if (i == fragmentIndex){
				fragmentTransaction.show(fragments[i]);
			}
			else{
				fragmentTransaction.hide(fragments[i]);
			}
		}
		if (addToBackStack){
			fragmentTransaction.addToBackStack(null);
		}
		fragmentTransaction.commit();
	}
	

	private void getAppKeyHash() {
	    try {
	        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
	        for (Signature signature : info.signatures) {
	            MessageDigest md;

	            md = MessageDigest.getInstance("SHA");
	            md.update(signature.toByteArray());
	            String something = new String(Base64.encode(md.digest(), 0));
	            Log.d("Hash key", something);
	        } 
	    }
	    catch (NameNotFoundException e1) {
	        // TODO Auto-generated catch block
	        Log.e("name not found", e1.toString());
	    }

	    catch (NoSuchAlgorithmException e) {
	        // TODO Auto-generated catch block
	        Log.e("no such an algorithm", e.toString());
	    }
	    catch (Exception e){
	        Log.e("exception", e.toString());
	    }

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if (fragments[SELECTION].isVisible()){
			if (menu.size() == 0){
				menuItemSettings = menu.add(R.string.settings);
			}
			return true;
		}
		else{
			menu.clear();
			menuItemSettings = null;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.equals(menuItemSettings)){
			showFragment(SETTINGS, true);
			return true;
		}
		return false;
	}
}
